<template>
  <div>
    <h1>{{ msg }}</h1>
    <p>{{ messages }}</p>
  </div>

</template>

<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue'

defineProps({
  msg: String,
})
const messages = ref([]);
const count = ref(0)
const source = ref()
const SSE = () => {
  if (window.EventSource) {//如果浏览器支持sse
    //建立连接
    source.value = new EventSource('https://localhost:7063/WeatherForecast/SSEtest')

    //连接一旦建立就会触发open事件
    source.value.onopen = function (e) {
      console.log('建立连接', e);
    }

    //收到服务端发来的消息
    source.value.onmessage = function (e) {
      messages.value += e.data;
      console.log('接收到消息', e);
      if (e.data === 'END') {
        source.value.close();
      }
    }

    source.value.onerror = function (e) {
      if (e.readyState == EventSource.CLOSED) {
        console.log('连接关闭');
      } else {
        console.log('发生错误', e);
      }
    }
  } else {
    console.log('浏览器不支持sse');
  }
}

onMounted(() => {
  SSE();
});


// 当组件卸载时，关闭EventSource连接
onBeforeUnmount(() => {
  source.value.close();
});

</script>

<style scoped></style>
